Save search results to database
- Under
db.mysqlpackage, create class/MySQLConnection.java. - Implement
DBConnectioninterface - Implement both
closemethod andconstructor.
1 | // connection |
- implement
searchItems()inMySQLConnection. Previously we callTicketMasterAPI.searchfrom ourSearchItemservlet directly. But actually our recommendation code also needs to call the same search function, so we make a designated function here to do the search call.
The code is simply copied from what we’ve already had inSearchItem.java.
1 | /** |
- after
searchItem, let’s trysaveItemto save data into database. Again, careful with the import suggestions. Always choosejava.sql.*.
1 | /** |
Use PreparedStatement and stmt.settring() can effectively avoid SQL injection.
PreparedStatement is faster than raw String. Only have to create it once.
- SQL injection. Turns the input to the SQL statement, and makes the query always true.
1 |
|
- update
DBConnectionFactory.
1 | public static DBConnection getConnection(String db) { |
- In
src/rpc/SearchItem.java, add a privatedbconnectionfield and updatedoGet().
1 | /** |
Implement set/unset favorite related functions
- let’s try setFavoriteItem and unsetFavoriteItem
1 | /** |
create a new servlet called
ItemHistory, update the url mapping to\historycreate a new function in RpcHelper.java to parse HTTP request body. Imagine the input HTTP request looks like:
1 | { |
1 | /** |
- update
doPost()anddoDeleteinItemHistory.javato use this new function.
1 | /** |
- open postman, switch to
postmethod, use http://localhost:8080/Jupiter/history, then copy the following JSON object into body. Replaceitem_id1anditem_id2with the realitem_idexist in your item table.
1 | { |
- now let’s send another request to test our delete function. Open another tab in postman, switch method to
delete, use http://localhost:8080/Jupiter/history, then copy the following JSON object into body. Again replaceitem_id1with the realitem_idexist in your history table.1
2
3
4
5
6{
'user_id':'1111',
'favorite' : [
'item_id1',
]
}